package com.foo.cms.service.impl;

import com.foo.cms.reqvo.*;
import com.foo.cms.service.ArticleService;
import com.foo.cms.service.BaseService;
import com.foo.cms.service.SetParamService;
import com.foo.cms.vo.Article;
import com.foo.cms.vo.Pager;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: LZS
 * Date: 12-6-23
 * Time: 下午1:21
 * To change this template use File | Settings | File Templates.
 */
@Service
public class ArticleServiceImpl extends BaseService implements ArticleService {

    private static final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class);

    @Resource
    private SetParamService setParamService;

    @Override
    public Pager listArticle(ArticleListReq req) {
        Pager pager = new Pager();
        List<Object> data = new ArrayList<Object>();
        StringBuilder sb = new StringBuilder();
        Map<String, Object> params = new HashMap<String, Object>();
        int page = req.getPage();
        int pagesize = req.getPagesize();
        String sortname = req.getSortname();
        String sortorder = req.getSortorder();
        if (StringUtils.isBlank(sortname)) {
            sortname = "numsort desc , datcreate desc";
        } else if (StringUtils.equalsIgnoreCase("sort", sortname)) {
            sortname = "numsort";
        } else if (StringUtils.equalsIgnoreCase("created", sortname)) {
            sortname = "datcreate";
        } else if (StringUtils.equalsIgnoreCase("click", sortname)) {
            sortname = "numclick";
        } else if (StringUtils.equalsIgnoreCase("status", sortname)) {
            sortname = "numstatus";
        } else if (StringUtils.equalsIgnoreCase("title", sortname)) {
            sortname = "vc2title";
        } else if (StringUtils.equalsIgnoreCase("type", sortname)) {
            sortname = "vc2type";
        } else if (StringUtils.equalsIgnoreCase("partName", sortname)) {
            sortname = "numpartid";
        }
        if (StringUtils.isBlank(sortorder)) {
            sortorder = "";
        }

        int startIndex = pagesize * (page - 1);
        int endIndex = page * pagesize;
        params.put("startIndex", startIndex);
        params.put("endIndex", endIndex);
        sb.append("from dt_article where VC2ENABLEFLAG='Y' ");
        String title = req.getTitle();
        if (!isBlank(title)) {
            sb.append("and vc2title like :title ");
            params.put("title", "%" + title + "%");
        }
        String type = req.getType();
        if (!isBlank(type)) {
            sb.append("and vc2type=:type ");
            params.put("type", type);
        }
        String partId = req.getPartId();
        if (!isBlank(partId)) {
            sb.append("and numpartid=:partId ");
            params.put("partId", partId);
        }
        String status = req.getStatus();
        if (!isBlank(status)) {
            sb.append("and numstatus=:status");
            params.put("status", status);
        }
        int total = jdbcTemplate.queryForInt("select count(*) " + sb.toString(), params);
        pager.setTotal(total);
        sb.append(" order by " + sortname + " " + sortorder);
        String sql = "select * from (select a.*,rownum rn from (select * " + sb.toString() + ") a where rownum < :endIndex) where rn > :startIndex";
        logger.info(params.toString());
        logger.info(sql);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, params);
        for (Map<String, Object> map : list) {
            Article rs = new Article();
            rs.setId(String.valueOf(map.get("numarticleid")));
            rs.setPartName(getPartName(map.get("numpartid")));
            rs.setClick(String.valueOf(map.get("numclick")));
            rs.setCreated(sdf2.format(map.get("datcreate")));
            rs.setSort(String.valueOf(map.get("numsort")));
            rs.setType(getType(map.get("vc2type")));
            rs.setTitle(String.valueOf(map.get("vc2title")));
            rs.setStatus(getStatus(map.get("numstatus")));
            data.add(rs);
        }
        pager.setRows(data);
        return pager;
    }

    @Override
    public int deleteArticle(String id) {
        String sql = "update dt_article set VC2ENABLEFLAG = 'N' where numarticleid in (" + id + ")";
        Map<String, Object> params = new HashMap<String, Object>();
        return jdbcTemplate.update(sql, params);
    }

    @Override
    public int examArticle(String ids, String status) {
        if (StringUtils.isNotBlank(ids)) {
            ids = StringUtils.substringBeforeLast(ids, ",");
            logger.info("examArticle update ids = " + ids);
            String sql = "update dt_article set numstatus=:status where numarticleid in (" + ids + ")";
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("status", status);
            return jdbcTemplate.update(sql, params);
        } else {
            return 0;
        }
    }


    @Override
    public int recommendArticle(String articleIds, String recommendId) {
        if (StringUtils.isNotBlank(articleIds)) {
            articleIds = StringUtils.substringBeforeLast(articleIds, ",");
            logger.info("recommendArticle update ids = " + articleIds);

            String[] articleIdArray = articleIds.split(",");
            if (articleIdArray != null && articleIdArray.length > 0) {
                for (String articleId : articleIdArray) {
                    if (StringUtils.isNotBlank(articleId) && StringUtils.isNumeric(articleId)) {
                        logger.info("recommendArticle update articleId = " + articleId + "," + recommendId);
                        addRecommend(recommendId, Long.parseLong(articleId));
                    }
                }
            }
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public int editSort(String id, String sort) {
        if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(sort)) {
            logger.info("editSort id = " + id + ", sort = " + sort);
            String sql = "update dt_article set numsort = :sort where numarticleid = :id";
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("id", id);
            params.put("sort", sort);
            return jdbcTemplate.update(sql, params);
        }
        return 0;
    }

    @Override
    public Article getArticle(String id) {
        Article article = new Article();
        Map<String, Object> params = new HashMap<String, Object>();
        String sql = "select * from dt_article where numarticleid = :articleid";
        params.put("articleid", id);
        article = jdbcTemplate.queryForObject(sql, params, new ArticleRowMapper());
        article.setPrefixPicUrl(setParamService.getParamByKey("PIC_URL").getValue());
        article.setPrefixVideoUrl(setParamService.getParamByKey("VIDEO_URL").getValue());
        return article;
    }

    @Transactional
    @Override
    public int addTextArticle(TextReq req, String uid) throws ParseException {
        Map<String, Object> params = new HashMap<String, Object>();
        String briefflag = req.getBriefflag();
        String summary = req.getSummary();
        if ("Y".equals(briefflag)) {
            String textContent = req.getTextContent();
            summary = textContent.length() > 20 ? textContent.substring(0, 20) : textContent;
        } else {
            briefflag = "N";
        }
        long id = genId();
        String sql = "insert into dt_article" +
                "(numarticleid,vc2title,vc2brieftitle,numsort,vc2type," +
                "vc2titlecolor,vc2titlestyle,vc2author,vc2source,vc2clickgourl," +
                "content,numpartid,vc2summary,datpublist,vc2uploader," +
                "vc2briefflag,vc2enableflag,datcreate,numclick,vc2staticflag,vc2pageflag,numstatus) values" +
                "(:id,:title,:brieftitle,:sort,:type," +
                ":titlecolor,:titlestyle,:author,:source,:clickgourl," +
                ":content,:partid,:summary,:publist,:uid," +
                ":briefflag,'Y',sysdate,0,'N','N',1)";

        params.put("id", id);
        params.put("title", req.getTitle());
        params.put("brieftitle", req.getBrieftitle());
        params.put("sort", req.getSort());
        params.put("type", req.getType());
        params.put("titlecolor", req.getTitlecolor());
        params.put("titlestyle", req.getTitlestyle());
        params.put("author", req.getAuthor());
        params.put("source", req.getSource());
        params.put("clickgourl", req.getClickgourl());
        params.put("content", req.getContent());
        params.put("partid", req.getPart());
        params.put("summary", summary);
        params.put("publist", StringUtils.isBlank(req.getPublist()) ? null : sdf2.parse(req.getPublist()));
        params.put("uid", uid);
        params.put("briefflag", briefflag);
        jdbcTemplate.update(sql, params);
        addCategory(req.getCategory(), id);
        addRecommend(req.getRecommend(), id);
        addArticles(req.getArtids(), id);
        addKeyword(req.getKeyword(), id);
        return 1;
    }


    @Transactional
    @Override
    public int addImageArticle(ImageReq req, String uid) throws IOException {
        long id = genId();
        //图片保存
        String picParam = setParamService.getParamByKey("PIC_PATH").getValue();
        MultipartFile[] pics = req.getPics();
        if (pics != null) {
            List<String> picPaths = new ArrayList<String>();
            for (MultipartFile pic : pics) {
                if (!pic.isEmpty()) {
                    String savePath = savePicFile(pic, picParam);
                    picPaths.add(savePath);
                }
            }
            addArtResource(picPaths, id);
        }
        //保存缩略图
        String thumbpicurl = "";
        MultipartFile pic = req.getSmallPic();
        if (!pic.isEmpty()) {
            thumbpicurl = savePicFile(pic, picParam);
        }

        Map<String, Object> params = new HashMap<String, Object>();
        String summary = req.getSummary();
        String sql = "insert into dt_article" +
                "(numarticleid,vc2title,vc2brieftitle,numsort,vc2type," +
                "vc2titlecolor,vc2titlestyle,vc2author,vc2source,vc2clickgourl," +
                "numpartid,vc2summary,datpublist,vc2uploader,VC2THUMBPICURL," +
                "vc2briefflag,vc2enableflag,datcreate,numclick,vc2staticflag," +
                "vc2pageflag,numstatus) values" +
                "(:id,:title,:brieftitle,:sort,:type," +
                ":titlecolor,:titlestyle,:author,:source,:clickgourl," +
                ":partid,:summary,:publist,:uid,:thumbpicurl," +
                ":briefflag,'Y',sysdate,0,'N'," +
                "'N',1)";

        params.put("id", id);
        params.put("title", req.getTitle());
        params.put("brieftitle", req.getBrieftitle());
        params.put("sort", req.getSort());
        params.put("type", req.getType());
        params.put("titlecolor", req.getTitlecolor());
        params.put("titlestyle", req.getTitlestyle());
        params.put("author", req.getAuthor());
        params.put("source", req.getSource());
        params.put("clickgourl", req.getClickgourl());
        params.put("partid", req.getPart());
        params.put("summary", summary);
        params.put("briefflag", isBlank(summary) ? "N" : "Y");
        try {
            params.put("publist", StringUtils.isBlank(req.getPublist()) ? null : sdf2.parse(req.getPublist()));
        } catch (ParseException e) {
            logger.error("", e);
            throw new RuntimeException("publist parse error!!!");
        }
        params.put("uid", uid);
        params.put("thumbpicurl", thumbpicurl);
        jdbcTemplate.update(sql, params);
        addRecommend(req.getRecommend(), id);
        addArticles(req.getArtids(), id);
        addKeyword(req.getKeyword(), id);
        return 1;
    }

    private String savePicFile(MultipartFile pic, String picParam) throws IOException {
        String fileName = pic.getOriginalFilename();
        String postfix = fileName.substring(fileName.lastIndexOf("."));
        String datePath = sdf.format(new Date()) + "/";
        String savePath = datePath + UUID.randomUUID() + postfix;
        if (!validateFileType(pic)) {
            throw new RuntimeException("上传文件类型错误！");
        }
        File dir = new File(picParam + datePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(picParam + savePath);//代表上传文件的目录
        FileOutputStream out = new FileOutputStream(file);
        InputStream in = pic.getInputStream();
        IOUtils.copy(in, out);
        IOUtils.closeQuietly(out);//关闭输出流
        IOUtils.closeQuietly(in);//关闭输出流
        return savePath;
    }

    private void addCategory(String categories, long artid) {
        if (!isBlank(categories)) {
            String sql = "delete dt_article_category where numarticleid=" + artid;
            jdbcTemplate.update(sql, new HashMap<String, Object>());
            String[] cats = categories.split(",");
            if (cats.length > 0) {
                sql = "insert into dt_article_category (numarcatid,numcategoryid,numarticleid) values(GLOBAL_SEQ.NEXTVAL,:catid,:artid)";
                Map[] map = new HashMap[cats.length];
                for (int i = 0; i < cats.length; i++) {
                    map[i] = new HashMap<String, Object>();
                    map[i].put("catid", cats[i]);
                    map[i].put("artid", artid);
                }
                jdbcTemplate.batchUpdate(sql, map);
            }
        }
    }

    private void addArtResource(List<String> picPaths, long artid) {
        String sql = "delete dt_article_resource where numarticleid=" + artid;
        jdbcTemplate.update(sql, new HashMap<String, Object>());
        sql = "insert into dt_article_resource(numartresid,numarticleid,vc2resourceurl,numsort,vc2enableflag, datcreatetime)" +
                "values(GLOBAL_SEQ.NEXTVAL,:artid,:resourceurl,:numsort,'Y',sysdate)";
        Map[] map = new HashMap[picPaths.size()];
        for (int i = 0; i < picPaths.size(); i++) {
            map[i] = new HashMap<String, Object>();
            map[i].put("artid", artid);
            map[i].put("resourceurl", picPaths.get(i));
            map[i].put("numsort", i);
        }
        jdbcTemplate.batchUpdate(sql, map);
    }

    private void addRecommend(String recommends, long artid) {
        if (!isBlank(recommends)) {
            String sql = "delete dt_article_recommend where numarticleid=" + artid;
            jdbcTemplate.update(sql, new HashMap<String, Object>());
            String[] recArray = recommends.split(",");
            if (recArray.length > 0) {
                sql = "insert into dt_article_recommend(numartrecoid,numarticleid,numrecommendid,datcreatetime)values(GLOBAL_SEQ.NEXTVAL,:artid,:recid,sysdate)";
                Map[] map = new HashMap[recArray.length];
                for (int i = 0; i < recArray.length; i++) {
                    map[i] = new HashMap<String, Object>();
                    map[i].put("recid", recArray[i]);
                    map[i].put("artid", artid);
                }
                jdbcTemplate.batchUpdate(sql, map);
            }
        }
    }

    private void addArticles(String artids, long artid) {
        logger.info("artids = " + artids);
        if (!isBlank(artids)) {
            String sql = "delete dt_article_related where numarticleid=" + artid;
            jdbcTemplate.update(sql, new HashMap<String, Object>());
            String[] artArray = artids.split(",");
            if (artArray.length > 0) {
                sql = "insert into dt_article_related (numartrelid,numarticleid)values(:relid,:artid)";
                Map[] map = new HashMap[artArray.length];
                for (int i = 0; i < artArray.length; i++) {
                    map[i] = new HashMap<String, Object>();
                    map[i].put("relid", artArray[i]);
                    map[i].put("artid", artid);
                }
                jdbcTemplate.batchUpdate(sql, map);
            }
        }
    }

    private void addKeyword(String keywords, long artid) {
        if (!isBlank(keywords)) {
            String sql = "delete dt_article_keyword where numarticleid=" + artid;
            jdbcTemplate.update(sql, new HashMap<String, Object>());

            keywords = StringUtils.replace(keywords, "，", ",");
            keywords = StringUtils.replace(keywords, "|", ",");
            keywords = StringUtils.replace(keywords, "；", ",");
            keywords = StringUtils.replace(keywords, ";", ",");

            String[] keywordArray = StringUtils.split(keywords, ",");
            if (keywordArray.length > 0) {
                sql = "select numkeywordid from dt_keyword where vc2keyword=:keyword";
                String sql2 = "insert into dt_article_keyword(numarkeyid,numarticleid,numkeywordid)values(GLOBAL_SEQ.NEXTVAL,:artid,:kid)";
                String sql3 = "insert into dt_keyword(numkeywordid,vc2keyword,datcreate,vc2enableflag)values(:id,:keyword,sysdate,'Y')";
                Map<String, Object> map = new HashMap<String, Object>();
                for (String keyword : keywordArray) {
                    map.put("keyword", keyword);
                    try {
                        long kid = jdbcTemplate.queryForLong(sql, map);
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("artid", artid);
                        params.put("kid", kid);
                        jdbcTemplate.update(sql2, params);
                    } catch (EmptyResultDataAccessException e) {
                        long kid = genId();
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("id", kid);
                        params.put("keyword", keyword);
                        jdbcTemplate.update(sql3, params);
                        params.put("artid", artid);
                        params.put("kid", kid);
                        jdbcTemplate.update(sql2, params);
                    }
                }
            }
        }
    }

    private long genId() {
        return jdbcTemplate.queryForLong("select GLOBAL_SEQ.NEXTVAL from dual", new HashMap<String, Object>());
    }


    @Override
    @Transactional
    public int addPicArticle(PictureReq req, String uid) {
        Map<String, Object> params = new HashMap<String, Object>();
        //保存图片和缩略图
        logger.info("reqvo = " + req.toString());

        MultipartFile thumbPicFile = req.getThumbPicFile();
        MultipartFile picFile = req.getPicFile();

        String picParam = setParamService.getParamByKey("PIC_PATH").getValue();
        //保存缩略图
        String thumbPicUrl = "";
        if (!thumbPicFile.isEmpty()) {
            try {
                thumbPicUrl = savePicFile(thumbPicFile, picParam);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //保存图片
        String picUrl = "";
        if (!picFile.isEmpty()) {
            try {
                picUrl = savePicFile(picFile, picParam);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        logger.info("thumbPicUrl = " + (thumbPicFile == null ? "" : thumbPicFile.getOriginalFilename()) + ", picUrl = " + (picFile == null ? "" : picFile.getOriginalFilename()));
        int result = 1;
        long id = genId();
        String briefflag = "N";
        if (StringUtils.isNotBlank(req.getSummary())) {
            briefflag = "Y";
        }
        try {
            String sql = "insert into dt_article" +
                    "(numarticleid,vc2title,vc2brieftitle,vc2titlecolor,vc2titlestyle,numsort,vc2type,vc2author,vc2source,vc2clickgourl,numpartid,vc2summary ,vc2uploader, datpublist , vc2thumbpicurl , vc2picurl , " +
                    "vc2briefflag,vc2enableflag,datcreate,numclick,vc2staticflag,vc2pageflag,numstatus ) values" +
                    "(:id,:title,:briefTitle,:titleColor,:titleStyle,:sort,:type,:author,:source,:clickGoUrl,:partId,:summary,:uid,:publist,:thumbpicurl,:picurl," +
                    ":briefflag,'Y',sysdate,0,'N','N',1)";
            params.put("id", id);
            params.put("title", req.getTitle());
            params.put("briefTitle", req.getBriefTitle());
            params.put("titleColor", req.getTitleColor());
            params.put("titleStyle", req.getTitleStyle());
            params.put("sort", req.getSort());
            params.put("type", req.getType());
            params.put("author", req.getAuthor());
            params.put("source", req.getSource());
            params.put("clickGoUrl", req.getClickGoUrl());
            params.put("partId", req.getPartId());
            params.put("summary", req.getSummary());
            params.put("uid", uid);
            params.put("publist", StringUtils.isBlank(req.getPublist()) ? null : sdf.parse(req.getPublist()));
            params.put("thumbpicurl", thumbPicUrl);
            params.put("picurl", picUrl);
            params.put("briefflag", briefflag);
            jdbcTemplate.update(sql, params);
        } catch (Exception e) {
            result = 0;
            e.printStackTrace();
            logger.error("addPicArticle Exception !!!", e);
        }

        return result;
    }

    @Override
    @Transactional
    public int addVideoArticle(VideoReq req, String uid) {
        Map<String, Object> params = new HashMap<String, Object>();
        //保存视频和缩略图
        logger.info("reqvo = " + req.toString());
        MultipartFile thumbPicFile = req.getThumbPicFile();
        MultipartFile videoFile = req.getVideoFile();
        String videoUrl = req.getVideoUrl();

        logger.info("thumbPicUrl = " + (thumbPicFile == null ? "" : thumbPicFile.getOriginalFilename()) + ", videoFile = " + (videoFile == null ? "" : videoFile.getOriginalFilename()) + " , videoUrl = " + videoUrl);
        String picParam = setParamService.getParamByKey("PIC_PATH").getValue();
        //保存缩略图
        String thumbPicUrl = "";
        if (!thumbPicFile.isEmpty()) {
            try {
                thumbPicUrl = savePicFile(thumbPicFile, picParam);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String videoParam = setParamService.getParamByKey("VIDEO_PATH").getValue();
        //保存视频
        String newVideoUrl = "";
        if (!videoFile.isEmpty()) {
            try {
                newVideoUrl = savePicFile(videoFile, videoParam);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            newVideoUrl = videoUrl;
        }
        int result = 1;
        long id = genId();
        String briefflag = "N";
        if (StringUtils.isNotBlank(req.getSummary())) {
            briefflag = "Y";
        }
        try {
            String sql = "insert into dt_article" +
                    "(numarticleid,vc2title,vc2brieftitle,vc2titlecolor,vc2titlestyle,numsort,vc2type,vc2author,vc2source,vc2clickgourl,numpartid,vc2summary ,vc2uploader, datpublist, vc2timelen, vc2thumbpicurl , vc2videourl, " +
                    "vc2briefflag,vc2enableflag,datcreate,numclick,vc2staticflag,vc2pageflag,numstatus ) values" +
                    "(:id,:title,:briefTitle,:titleColor,:titleStyle,:sort,:type,:author,:source,:clickGoUrl,:partId,:summary,:uid,:publist,:timeLen,:thumbpicurl,:videourl," +
                    ":briefflag,'Y',sysdate,0,'N','N',1)";
            params.put("id", id);
            params.put("title", req.getTitle());
            params.put("briefTitle", req.getBriefTitle());
            params.put("titleColor", req.getTitleColor());
            params.put("titleStyle", req.getTitleStyle());
            params.put("sort", req.getSort());
            params.put("type", req.getType());
            params.put("author", req.getAuthor());
            params.put("source", req.getSource());
            params.put("clickGoUrl", req.getClickGoUrl());
            params.put("partId", req.getPartId());
            params.put("summary", req.getSummary());
            params.put("publist", StringUtils.isBlank(req.getPublist()) ? null : sdf.parse(req.getPublist()));
            params.put("timeLen", req.getTimeLen());
            params.put("uid", uid);
            params.put("thumbpicurl", thumbPicUrl);
            params.put("videourl", videoUrl);
            params.put("briefflag", briefflag);
            jdbcTemplate.update(sql, params);
            addRecommend(req.getRecommend(), id);
            addArticles(req.getArtids(), id);
            addKeyword(req.getKeyword(), id);
        } catch (Exception e) {
            result = 0;
            e.printStackTrace();
            logger.error("addVideoArticle Exception !!!", e);
        }
        return result;
    }

    @Override
    public int editPicArticle(PictureReq req, String uid) {
        Map<String, Object> params = new HashMap<String, Object>();
        //保存图片和缩略图
        logger.info("reqvo = " + req.toString());

        MultipartFile thumbPicFile = req.getThumbPicFile();
        MultipartFile picFile = req.getPicFile();

        String picParam = setParamService.getParamByKey("PIC_PATH").getValue();
        //保存缩略图
        String thumbPicUrl = req.getThumbPicUrl();
        if (!thumbPicFile.isEmpty()) {
            try {
                thumbPicUrl = savePicFile(thumbPicFile, picParam);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //保存图片
        String picUrl = req.getPicUrl();
        if (!picFile.isEmpty()) {
            try {
                picUrl = savePicFile(picFile, picParam);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        logger.info("thumbPicUrl = " + (thumbPicFile == null ? "" : thumbPicFile.getOriginalFilename()) + ", picUrl = " + (picFile == null ? "" : picFile.getOriginalFilename()));
        int result = 1;
        long id = Long.parseLong(req.getId());
        String briefflag = "N";
        if (StringUtils.isNotBlank(req.getSummary())) {
            briefflag = "Y";
        }
        try {
            String sql = "update dt_article set vc2title = :title ,vc2brieftitle = :briefTitle ,vc2titlecolor = :titleColor ,vc2titlestyle = :titleStyle ,numsort = :sort," +
                    "vc2type = :type ,vc2author = :author ,vc2source = :source ,vc2clickgourl = :clickGoUrl ,numpartid = :partId,vc2summary = :summary ,vc2uploader = :uid , vc2thumbpicurl = :thumbpicurl , " +
                    "vc2picurl = :picurl , vc2briefflag = :briefflag , datpublist = :publist where numarticleid = :id";
            params.put("id", id);
            params.put("title", req.getTitle());
            params.put("briefTitle", req.getBriefTitle());
            params.put("titleColor", req.getTitleColor());
            params.put("titleStyle", req.getTitleStyle());
            params.put("sort", req.getSort());
            params.put("type", req.getType());
            params.put("author", req.getAuthor());
            params.put("source", req.getSource());
            params.put("clickGoUrl", req.getClickGoUrl());
            params.put("partId", req.getPartId());
            params.put("summary", req.getSummary());
            params.put("uid", uid);
            params.put("thumbpicurl", thumbPicUrl);
            params.put("picurl", picUrl);
            params.put("publist", StringUtils.isBlank(req.getPublist()) ? null : sdf.parse(req.getPublist()));
            params.put("briefflag", briefflag);
            jdbcTemplate.update(sql, params);

        } catch (Exception e) {
            result = 0;
            e.printStackTrace();
            logger.error("editPicArticle Exception !!!", e);
        }

        return result;

    }

    @Override
    public int editVideoArticle(VideoReq req, String uid) {
        Map<String, Object> params = new HashMap<String, Object>();
        //保存视频和缩略图
        logger.info("reqvo = " + req.toString());
        MultipartFile thumbPicFile = req.getThumbPicFile();
        MultipartFile videoFile = req.getVideoFile();
        String videoUrl = req.getVideoUrl();

        logger.info("thumbPicUrl = " + (thumbPicFile == null ? "" : thumbPicFile.getOriginalFilename()) + ", videoFile = " + (videoFile == null ? "" : videoFile.getOriginalFilename()) + " , videoUrl = " + videoUrl);
        String picParam = setParamService.getParamByKey("PIC_PATH").getValue();
        //保存缩略图
        String thumbPicUrl = "";
        if (!thumbPicFile.isEmpty()) {
            try {
                thumbPicUrl = savePicFile(thumbPicFile, picParam);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String videoParam = setParamService.getParamByKey("VIDEO_PATH").getValue();
        //保存视频
        String newVideoUrl = "";
        if (!videoFile.isEmpty()) {
            try {
                newVideoUrl = savePicFile(videoFile, videoParam);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            newVideoUrl = videoUrl;
        }
        int result = 1;
        long id = Long.parseLong(req.getId());
        String briefflag = "N";
        if (StringUtils.isNotBlank(req.getSummary())) {
            briefflag = "Y";
        }
        try {
            String sql = "update dt_article set vc2title = :title ,vc2brieftitle = :briefTitle,vc2titlecolor = :titleColor,vc2titlestyle = :titleStyle , " +
                    "numsort = :sort,vc2type = :type ,vc2author = :author,vc2source = :source,vc2clickgourl = :clickGoUrl,numpartid = :partId,vc2summary = :summary ," +
                    "vc2uploader = :uid, datpublist = :publist, vc2timelen = :timeLen , vc2thumbpicurl = :thumbpicurl , vc2videourl = :videourl , " +
                    "vc2briefflag = :briefflag where numarticleid = :id";
            params.put("id", id);
            params.put("title", req.getTitle());
            params.put("briefTitle", req.getBriefTitle());
            params.put("titleColor", req.getTitleColor());
            params.put("titleStyle", req.getTitleStyle());
            params.put("sort", req.getSort());
            params.put("type", req.getType());
            params.put("author", req.getAuthor());
            params.put("source", req.getSource());
            params.put("clickGoUrl", req.getClickGoUrl());
            params.put("partId", req.getPartId());
            params.put("summary", req.getSummary());
            params.put("publist", StringUtils.isBlank(req.getPublist()) ? null : sdf.parse(req.getPublist()));
            params.put("timeLen", req.getTimeLen());
            params.put("uid", uid);
            params.put("thumbpicurl", thumbPicUrl);
            params.put("videourl", videoUrl);
            params.put("briefflag", briefflag);
            jdbcTemplate.update(sql, params);
            addRecommend(req.getRecommend(), id);
            addArticles(req.getArtids(), id);
            addKeyword(req.getKeyword(), id);
        } catch (Exception e) {
            result = 0;
            e.printStackTrace();
            logger.error("addVideoArticle Exception !!!", e);
        }

        return result;
    }

    @Override
    @Transactional
    public int editTextArticle(TextReq req, String uid) throws ParseException {
        Map<String, Object> params = new HashMap<String, Object>();
        String briefflag = req.getBriefflag();
        String summary = "";
        if ("Y".equals(briefflag)) {
            String textContent = req.getTextContent();
            summary = textContent.length() > 20 ? textContent.substring(0, 20) : textContent;
        } else {
            briefflag = "N";
        }

        long id = req.getId();

        String sql = "update dt_article set vc2title=:title,vc2brieftitle=:brieftitle,numsort=:sort,vc2type=:type," +
                "vc2titlecolor=:titlecolor,vc2titlestyle=:titlestyle,vc2author=:author,vc2source=:source,vc2clickgourl=:clickgourl," +
                "content=:content,numpartid=:partid,vc2summary=:summary,datpublist=:publist,vc2uploader=:uid," +
                "vc2briefflag=:briefflag where numarticleid=:id";

        params.put("id", id);
        params.put("title", req.getTitle());
        params.put("brieftitle", req.getBrieftitle());
        params.put("sort", req.getSort());
        params.put("type", req.getType());
        params.put("titlecolor", req.getTitlecolor());
        params.put("titlestyle", req.getTitlestyle());
        params.put("author", req.getAuthor());
        params.put("source", req.getSource());
        params.put("clickgourl", req.getClickgourl());
        params.put("content", req.getContent());
        params.put("partid", req.getPart());
        params.put("summary", summary);
        params.put("publist", isBlank(req.getPublist()) ? null : sdf2.parse(req.getPublist()));
        params.put("uid", uid);
        params.put("briefflag", briefflag);
        int i = jdbcTemplate.update(sql, params);
        logger.info("article update row=" + i);
        addCategory(req.getCategory(), id);
        addRecommend(req.getRecommend(), id);
        addArticles(req.getArtids(), id);
        addKeyword(req.getKeyword(), id);
        return 1;

    }

    @Override
    @Transactional
    public int editImageArticle(ImageReq req, String uid) throws IOException, ParseException {
        long id = req.getId();
        //图片保存
        String picParam = setParamService.getParamByKey("PIC_PATH").getValue();
        MultipartFile[] pics = req.getPics();
        List<String> picPaths = new ArrayList<String>();
        if (pics != null) {
            for (MultipartFile pic : pics) {
                if (!pic.isEmpty()) {
                    String savePath = savePicFile(pic, picParam);
                    picPaths.add(savePath);
                }
            }
        }
        String[] oldPics = req.getOldpics();
        if (oldPics != null) {
            picPaths.addAll(Arrays.asList(oldPics));
        }
        addArtResource(picPaths, id);

        //保存缩略图
        String thumbpicurl = "";
        MultipartFile pic = req.getSmallPic();
        if (!pic.isEmpty()) {
            thumbpicurl = savePicFile(pic, picParam);
        } else {
            thumbpicurl = req.getOldsmallPic();
        }

        Map<String, Object> params = new HashMap<String, Object>();
        String summary = req.getSummary();

        String sql = "update dt_article set " +
                "vc2title=:title,vc2brieftitle=:brieftitle,numsort=:sort,vc2type=:type,vc2titlecolor=:titlecolor," +
                "vc2titlestyle=:titlestyle,vc2author=:author,vc2source=:source,vc2clickgourl=:clickgourl," +
                "numpartid=:partid,vc2summary=:summary,datpublist=:publist,vc2uploader=:uid,VC2THUMBPICURL=:thumbpicurl," +
                "vc2pageflag=:briefflag where numarticleid=:id";

        params.put("id", id);
        params.put("title", req.getTitle());
        params.put("brieftitle", req.getBrieftitle());
        params.put("sort", req.getSort());
        params.put("type", req.getType());
        params.put("titlecolor", req.getTitlecolor());
        params.put("titlestyle", req.getTitlestyle());
        params.put("author", req.getAuthor());
        params.put("source", req.getSource());
        params.put("clickgourl", req.getClickgourl());
        params.put("partid", req.getPart());
        params.put("summary", summary);
        params.put("briefflag", isBlank(summary) ? "N" : "Y");
        params.put("publist", StringUtils.isBlank(req.getPublist()) ? null : sdf2.parse(req.getPublist()));
        params.put("uid", uid);
        params.put("thumbpicurl", thumbpicurl);
        jdbcTemplate.update(sql, params);
        addRecommend(req.getRecommend(), id);
        addArticles(req.getArtids(), id);
        addKeyword(req.getKeyword(), id);
        return 1;
    }
}


class ArticleRowMapper implements RowMapper<Article> {
    @Override
    public Article mapRow(ResultSet rs, int rowNum) throws SQLException {
        Article article = new Article();
        article.setId(rs.getString("numarticleid"));
        article.setTitle(rs.getString("vc2title"));
        article.setBriefTitle(rs.getString("vc2brieftitle"));
        article.setTitleColor(rs.getString("vc2titlecolor"));
        article.setTitleStyle(rs.getString("vc2titlestyle"));
        article.setSort(rs.getString("numsort"));
        article.setType(rs.getString("vc2type"));
        article.setAuthor(rs.getString("vc2author"));
        article.setSource(rs.getString("vc2source"));
        article.setClickGoUrl(rs.getString("vc2clickgourl"));
        article.setPartId(rs.getString("numpartid"));
        article.setSummary(rs.getString("vc2summary"));
        article.setPublist(rs.getTimestamp("datpublist") == null ? "" : DateFormatUtils.format(rs.getTimestamp("datpublist"), "yyyy-MM-dd HH:mm"));
        article.setTimeLen(rs.getString("vc2timelen"));
        article.setUid(rs.getString("vc2uploader"));
        article.setThumbPicUrl(rs.getString("vc2thumbpicurl"));
        article.setVideoUrl(rs.getString("vc2picurl"));
        article.setBriefFlag(rs.getString("vc2briefflag"));
        article.setContent(rs.getString("content"));
        return article;
    }


}
